﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Utility;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Common.Exchange;
using Telerik.WebControls;
using System.Data;

namespace Runda.CMS.Portal.NoticeManage
{
    public partial class NoticeSend : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetEmployeesByDept();

                RadTreeView radTree = (RadTreeView)RadComboBox1.SelectedItem.FindControl("RadTreeView1");
                GenerateTreeView(radTree);
                loadContent();
            }
        }

        public void loadContent() {
            if (Request.QueryString["sendType"] == "maintainBill")
            {
                NoticeContent.InnerHtml = "<a href='#' target='_blank' onclick=\"javascript:window.open('/ContractFollowUp/MaintainBasic.aspx?RegisterID=" + Request.QueryString["RegisterID"] + "')\">查看单据</a>";
            }
        }
        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            Save();
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('操作成功');document.getElementById('ctl00_cphFormArea_btnRefersh').click();", true);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            Save();

            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "document.getElementById('ctl00_cphFormArea_btnRefersh').click();window.close();", true);
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            Save();

            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "document.getElementById('ctl00_cphFormArea_btnRefersh').click();alert('操作成功');", true);
        }

        private void Save()
        {
            SystemBll noticeBll = new SystemBll();

            CtrtMyNoticeEntity noticeEntity = new CtrtMyNoticeEntity();

            noticeEntity.CreatedBy = base.CurrentUserID;
            noticeEntity.CreatedOn = System.DateTime.Now;
            if (NoticeTime.Text != "")
            {
                noticeEntity.NoticeTime = System.Convert.ToDateTime(NoticeTime.Text);
            }
            else {
                noticeEntity.NoticeTime = System.DateTime.Now;
            }
            noticeEntity.Deleted = false;
            noticeEntity.NoticeContent = hiddenContent.Text.Trim();
            noticeEntity.NoticeID = Guid.NewGuid();
            noticeEntity.NoticeType = System.Convert.ToInt32(Enumerator.NoticeMessageType.Private);

            if (hiddenContent.Text.Trim()=="")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('请输入消息内容');", true);
                return;
            }

            if(employees.Items.Count <=0){
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('请选择接受人');", true);
                return;
            }
            List<CtrtMyNoticeUserEntity> noticeUsers = new List<CtrtMyNoticeUserEntity>();
            for (int index = 0; index < employees.Items.Count; index++) {
                CtrtMyNoticeUserEntity noticeUserEntity = new CtrtMyNoticeUserEntity();
                noticeUserEntity.ID = Guid.NewGuid();
                noticeUserEntity.NoticeID = noticeEntity.NoticeID;
                noticeUserEntity.Status = System.Convert.ToInt32(Enumerator.NoticeMessageStatus.unread);
                noticeUserEntity.UserID = new Guid(employees.Items[index].Value);
                noticeEntity.Deleted = false;
                noticeUsers.Add(noticeUserEntity);

                SysUserEntity user = new SysUserBll().Get<SysUserEntity>(new Guid(employees.Items[index].Value));
                MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, user.Email, noticeEntity.NoticeContent);
            }
            noticeEntity.CtrtMyNoticeUserEntityList = noticeUsers;
            noticeBll.createMyNotice(noticeEntity);
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            for (int index = 0; index < employeeChoose.Items.Count; index++)
            {
                if (employeeChoose.Items[index].Selected)
                {
                    bool isExist = false;
                    for (int i = 0; i < employees.Items.Count; i++)
                    {
                        if (employeeChoose.Items[index].Value == employees.Items[i].Value)
                        {
                            isExist = true;
                        }
                    }
                    if (!isExist)
                    {
                        ListItem item = new ListItem();
                        item.Text = employeeChoose.Items[index].Text;
                        item.Value = employeeChoose.Items[index].Value;
                        employees.Items.Add(item);
                    }
                }
            }
        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            List<ListItem> items = new List<ListItem>();
            for (int index = 0; index < employees.Items.Count; index++)
            {
                if (!employees.Items[index].Selected)
                {
                    items.Add(new ListItem(employees.Items[index].Text, employees.Items[index].Value));
                }
            }
            employees.Items.Clear();
            for (int index = 0; index < items.Count; index++)
            {
                employees.Items.Add(items[index]);
            }
        }

        #region GenerateTreeView

        private void GenerateTreeView(RadTreeView tree)
        {
            tree.Nodes.Clear();

            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = new SqlDbParameter();
            parm.ColumnName = "Deleted";
            parm.ColumnType = DbType.Boolean;
            parm.ParameterName = "@Deleted";
            parm.ParameterValue = false;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            List<SysDepartmentEntity> DeptList = new SysDepartmentBll().GetAll<SysDepartmentEntity>(parms, "Order By DepartmentName Asc");

            List<SysDepartmentEntity> SubDeptList = DeptList.FindAll(delegate(SysDepartmentEntity e) { return e.ParentID == Guid.Empty; });
            foreach (SysDepartmentEntity ent in SubDeptList)
            {
                RadTreeNode node = CreateNode(ent.DepartmentName, ent.DepartmentName, true, ent.DepartmentID.ToString(), true);
                tree.Nodes.Add(node);

                RecursivelyPopulate(DeptList, node, true);
            }
  
        }

        private void RecursivelyPopulate(List<SysDepartmentEntity> DeptList, RadTreeNode node, bool CanEdit)
        {
            List<SysDepartmentEntity> SubDeptList = DeptList.FindAll(delegate(SysDepartmentEntity e) { return e.ParentID == new Guid(node.Value); });

            foreach (SysDepartmentEntity ent in SubDeptList)
            {
                RadTreeNode radTreeNode = CreateNode(ent.DepartmentName, ent.DepartmentName, true, ent.DepartmentID.ToString(), CanEdit);

                node.Nodes.Add(radTreeNode);
                RecursivelyPopulate(DeptList, radTreeNode, true);
            }
        }

        private RadTreeNode CreateNode(string text, string toolTip, bool expanded, string id, bool CanEdit)
        {
            RadTreeNode node = new RadTreeNode(text, id);
            node.Expanded = expanded;

            if (CanEdit)
            {
                node.ContextMenuName = "Management";
            }

            //if (id.ToLower() == Enumerator.PlanningFolderSystemId.SharedFolderId.ToLower())
            //{
            //    node.ImageUrl = "../Images/ico/ico_16_OrgChart.gif";
            //}
            //else if (id.ToLower() == Enumerator.PlanningFolderSystemId.DraftFolderId.ToLower())
            //{
            //    node.ImageUrl = "../Images/ico/ico_16_OrgChart.gif";
            //}

            return node;
        }

        #endregion

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            GetEmployeesByDept();
        }

        private void GetEmployeesByDept()
        {
            SystemBll bll = new SystemBll();

            DataTable dt = null;
            if (hidSelected.Value != "")
            {
                dt = bll.GetUsersByDeptID(new Guid(hidSelected.Value));
            }
            else
            {
                dt = bll.GetUsersByDeptID(Guid.Empty);
            }

            employeeChoose.DataSource = dt;
            employeeChoose.DataTextField = "UserName";
            employeeChoose.DataValueField = "UserID";
            employeeChoose.DataBind();

        }
    }
}
